#!/usr/bin/env python
# coding:utf-8

import unittest
from sql_rice import db
from sql_rice import utils


class TestDbSet(unittest.TestCase):

    def setUp(self):
        self.statement = {'select': 'select rut, nombre from empleados ' +
        'where rut=:rut;',
            'insert': 'insert into empleados values(:rut, :nombre);',
            'delete': 'delete from empleados where rut=:rut;',
            'update': 'update empleados set nombre=:nombre where rut=:rut;'}
        self.script = '''PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE empleados(
                      rut text,
                      nombre text);
INSERT INTO "empleados" VALUES('1111','koke');
INSERT INTO "empleados" VALUES('2222','trinidad');
ANALYZE sqlite_master;
INSERT INTO "sqlite_stat1" VALUES('empleados',NULL,'2');
COMMIT;'''

    def test_search(self):
        with utils.TempDb(self.script) as tmp:
            dbset = db.DBSET(self.statement, {'database': tmp.path}, 'sqlite3')
            found = {'rut': '1111', 'nombre': 'koke'}
            self.assertDictEqual(found, dbset.search({'rut': '1111'})[0])

    def test_update(self):
        with utils.TempDb(self.script) as tmp:
            dbset = db.DBSET(self.statement, {'database': tmp.path}, 'sqlite3')
            found = {'nombre': 'eustaquio', 'rut': '1111'}
            dbset.update(found)
            self.assertDictEqual(found, dbset.search({'rut': '1111'})[0])

    def test_new(self):
        with utils.TempDb(self.script) as tmp:
            dbset = db.DBSET(self.statement, {'database': tmp.path}, 'sqlite3')
            values = {'rut': '3333', 'nombre': 'Juan Pineda'}
            dbset.new(values)

            self.assertDictEqual(values, dbset.search({'rut': '3333'})[0])

    def test_delete(self):
        with utils.TempDb(self.script) as tmp:
            dbset = db.DBSET(self.statement, {'database': tmp.path}, 'sqlite3')
            values = {'rut': '1111'}
            dbset.delete(values)
            self.assertEqual((), dbset.search(values))
